﻿using Ardalis.Specification;
using AutoMapper;
using System.Linq.Expressions;

namespace HuaweiCloud.Dotnet.Samples.Common
{
    public abstract class CrudApplicationServiceBase<T, TCreateDto, TUpdateDto, TDto> 
        : ICrudApplicationService<T, TCreateDto, TUpdateDto, TDto> 
        where T : class
    {
        protected readonly IRepository<T> _repository;
        protected readonly IMapper _mapper;
        protected CrudApplicationServiceBase(IRepository<T> repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        public virtual async Task AddAsync(TCreateDto t, CancellationToken token = default)
        {
            var item = _mapper.Map<T>(t);
            await _repository.AddAsync(item, token);
        }

        public virtual async Task UpdateAsync(TUpdateDto t, CancellationToken token = default)
        {
            var item = _mapper.Map<T>(t);
            await _repository.UpdateAsync(item, token);
        }

        public virtual async Task<TDto?> GetAsync<TID>(TID id, CancellationToken token) where TID : notnull
        {
            var item = await _repository.GetByIdAsync(id);
            return _mapper.Map<TDto>(item);
        }

        public virtual async Task<List<TDto>> ListAsync(ISpecification<T>? specification = null, CancellationToken token = default)
        {
            List<T> list;
            if (specification != null)
                list = await _repository.ListAsync(specification, token);
            else
                list = await _repository.ListAsync(token);
            return _mapper.Map<List<TDto>>(list);
        }

        public virtual async Task DeleteAsync<TID>(TID id, CancellationToken token = default) where TID : notnull
        {
            var item = await _repository.GetByIdAsync(id, token);
            if (item != null)
                await _repository.DeleteAsync(item, token);
        }
    }
}
